package com.simulation.web.controller.tech;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.simulation.common.core.domain.AjaxResult;
import com.simulation.common.core.domain.entity.SysUser;
import com.simulation.common.core.domain.model.LoginUser;
import com.simulation.common.utils.CoderUtils;
import com.simulation.common.utils.GiteaUtils;
import com.simulation.common.utils.SecurityUtils;
import com.simulation.common.utils.StringUtils;
import com.simulation.system.service.ISysUserService;
import com.simulation.web.dto.TechPostDTO;
import com.simulation.web.domain.TechPost;
import com.simulation.common.core.controller.BaseController;
import com.simulation.web.service.PostService;
import com.simulation.web.service.impl.MinioTemplate;
import com.simulation.web.utils.PostStatusEnum;
import com.simulation.web.utils.PromptConstants;
import com.simulation.web.vo.TechPostVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Api("项目管理")
@RestController
@RequestMapping("techPost")
public class TechPostController extends BaseController {

    @Resource
    private PostService postService;

    @Resource
    private MinioTemplate minioTemplate;

    @Resource
    private ISysUserService sysUserService;

    @Value("${edit.url}")
    private String editUrl;

    @Value("${oss.bucketName}")
    private String bucketName;

    @GetMapping("list")
    @ApiOperation("获取项目列表")
    public AjaxResult listAll() {
        return AjaxResult.success(postService.listAll());
    }

    /**
     * 分页查询
     * @param techPostDTO
     * @return
     */
    @GetMapping("getPage")
    @ApiOperation("分页查询项目")
    public AjaxResult getPage(TechPostDTO techPostDTO) {
        return AjaxResult.success(postService.getPage(techPostDTO));
    }

    /**
     * 根据主键查询
     *
     * @param techPostDTO
     * @return 返回记录，没有返回null
     */
    @GetMapping("getById")
    @ApiOperation("查询项目详情")
    public AjaxResult getById(TechPostDTO techPostDTO) {
        TechPostVO techPostVO = postService.getById(techPostDTO.getId());
        if (techPostVO == null) {
            return AjaxResult.warn(PromptConstants.PROJECT_NOT_EXIST);
        }
        // 查看当前项目是否被当前用户收藏
        techPostVO.setIsCopy(postService.isCopy(SecurityUtils.getUserId(), techPostDTO.getId()));
        // 编辑器地址
        techPostVO.setEditUrl(editUrl);
        // 工程模板下载地址
//        if (StrUtil.isBlank(techPostVO.getCode())) {
//            techPostVO.setCode(minioTemplate.getPresignedObjectUrl(bucketName, "template/projectTemplate.zip", 3600));
//        } else {
//            techPostVO.setCode(minioTemplate.getPresignedObjectUrl(bucketName, techPostVO.getCode().substring(1), 3600));
//        }
        if (StrUtil.isNotBlank(techPostVO.getEvaluateUrl()) && techPostVO.getEvaluateUrl().startsWith("https://isp.yunfengcloud.cn/file/")) {
            String data = techPostVO.getEvaluateUrl().replace("https://isp.yunfengcloud.cn/file/yunfeng/","");
            techPostVO.setEvaluateUrl(minioTemplate.getPresignedObjectUrl(bucketName, data.substring(0, data.indexOf("?")), 3600));
        } else if(StrUtil.isNotBlank(techPostVO.getEvaluateUrl())) {
            techPostVO.setEvaluateUrl(minioTemplate.getPresignedObjectUrl(bucketName, techPostVO.getEvaluateUrl().substring(1), 3600));
        }
//        if (StrUtil.isNotBlank(techPostVO.getCode()))
//            techPostVO.setCode(techPostVO.getCode().replace("http://43.138.128.114:9000/","https://isp.yunfengcloud.cn/file/"));
        if (StrUtil.isNotBlank(techPostVO.getEvaluateUrl()))
            techPostVO.setEvaluateUrl(techPostVO.getEvaluateUrl().replace("http://43.138.128.114:9000/","https://isp.yunfengcloud.cn/file/"));
        return AjaxResult.success(techPostVO);
    }

    /**
     * 新增，忽略null字段
     *
     * @param techPostDTO 新增的记录
     * @return 返回影响行数
     */
    @PostMapping("insert")
    @ApiOperation("新增项目")
    public AjaxResult insert(@RequestBody TechPostDTO techPostDTO) {
        TechPost techPost = new TechPost();
        BeanUtil.copyProperties(techPostDTO, techPost);
        postService.insertIgnoreNull(techPost, bucketName);

        TechPostVO techPostVO = new TechPostVO();
        BeanUtil.copyProperties(techPost, techPostVO);
        // 编辑器地址
        techPostVO.setEditUrl(editUrl);
        // 工程模板下载地址
//        if (StrUtil.isBlank(techPostVO.getCode())) {
//            techPostVO.setCode(minioTemplate.getPresignedObjectUrl(bucketName, "template/projectTemplate.zip", 3600));
//        } else {
//            techPostVO.setCode(minioTemplate.getPresignedObjectUrl(bucketName, techPostVO.getCode().substring(1), 3600));
//        }
        if (StrUtil.isNotBlank(techPostVO.getEvaluateUrl())) {
            techPostVO.setEvaluateUrl(minioTemplate.getPresignedObjectUrl(bucketName, techPostVO.getEvaluateUrl().substring(1), 3600));
        }
        return AjaxResult.success(techPostVO);
    }

    /**
     * 修改，忽略null字段
     *
     * @param techPostDTO 修改的记录
     * @return 返回影响行数
     */
    @PostMapping("update")
    @ApiOperation("修改项目信息")
    public AjaxResult update(@RequestBody TechPostDTO techPostDTO) {
        TechPost techPost = new TechPost();
        BeanUtil.copyProperties(techPostDTO, techPost);
        // 如果需要更新项目资源，需先删除旧的资源
        if (StrUtil.isNotBlank(techPostDTO.getCode())) {
            TechPostVO oldPost = postService.getById(techPostDTO.getId());
            // TODO 删除文件服务中对应的资源
            minioTemplate.removeFile(oldPost.getCode());
        }
        postService.updateIgnoreNull(techPost);

        TechPostVO techPostVO = new TechPostVO();
        BeanUtil.copyProperties(techPost, techPostVO);
        // 编辑器地址
        techPostVO.setEditUrl(editUrl);
        // 工程模板下载地址
//        if (StrUtil.isBlank(techPostVO.getCode())) {
//            techPostVO.setCode(minioTemplate.getPresignedObjectUrl(bucketName, "template/projectTemplate.zip", 3600));
//        } else {
//            techPostVO.setCode(minioTemplate.getPresignedObjectUrl(bucketName, techPostVO.getCode().substring(1), 3600));
//        }
        if (StrUtil.isNotBlank(techPostVO.getEvaluateUrl())) {
            techPostVO.setEvaluateUrl(minioTemplate.getPresignedObjectUrl(bucketName, techPostVO.getEvaluateUrl().substring(1), 3600));
        }
        return AjaxResult.success(techPostVO);
    }

    @PostMapping("evaluatePost")
    @ApiOperation("项目评测")
    public AjaxResult evaluatePost(@RequestBody TechPostDTO techPostDTO) {
        TechPost techPost = new TechPost();
        BeanUtil.copyProperties(techPostDTO, techPost);
        postService.updateIgnoreNull(techPost);
        return AjaxResult.success();
    }

    /**
     * 删除记录（软删除）
     *
     * @param techPostDTO 待删除的记录
     * @return 返回影响行数
     */
    @PostMapping("delete")
    @ApiOperation("删除项目")
    public AjaxResult delete(@RequestBody TechPostDTO techPostDTO) {
        TechPost techPost = new TechPost();
        TechPostVO old = postService.getById(techPostDTO.getId());
        BeanUtil.copyProperties(techPostDTO, techPost);
        postService.delete(techPost);
        // TODO 删除文件服务中对应的资源
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = sysUserService.selectUserPassnoById(loginUser.getUserId());
        CoderUtils.deleteWorkspace(old.getWorkspaceId());
        GiteaUtils.delGiteaRepo(sysUser.getUserName(), sysUser.getPassno(),String.valueOf(techPostDTO.getId()));
        return AjaxResult.success();
    }

    /**
     * 查询用户关注的项目
     * @param techPostDTO
     * @return
     */
    @GetMapping("getPostByUserFocusd")
    @ApiOperation("查询用户关注的项目")
    public AjaxResult getPostByUserFocusd(TechPostDTO techPostDTO) {
        return AjaxResult.success(postService.getPostByUserFocused(techPostDTO.getPageNum(), techPostDTO.getPageSize(), techPostDTO.getUserId()));
    }

    /**
     * 获取用户点赞的项目
     * @param techPostDTO
     * @return
     */
    @GetMapping("getPostByUserLikes")
    @ApiOperation("查询用户点赞的项目")
    public AjaxResult getPostByUserLikes(TechPostDTO techPostDTO) {
        return AjaxResult.success(postService.getPostByUserLikes(techPostDTO.getPageNum(), techPostDTO.getPageSize(), techPostDTO.getUserId()));
    }

    /**
     * 获取当前合集的项目
     * @param techPostDTO
     * @return
     */
    @GetMapping("getPostByCollectionId")
    @ApiOperation("查询当前合集的项目")
    public AjaxResult getPostByCollectionId(TechPostDTO techPostDTO) {
        return AjaxResult.success(postService.getPostByCollectionId(techPostDTO.getCollectionId(), techPostDTO.getPageNum(), techPostDTO.getPageSize()));
    }

    /**
     * 排行榜
     * @return
     */
    @GetMapping("/view-count")
    @ApiOperation("首页排行榜")
    public AjaxResult viewCount() {
        return AjaxResult.success(postService.selectViewCount());
    }

    /**
     * 推荐榜
     * @return
     */
    @GetMapping("/favorite-count")
    @ApiOperation("首页推荐榜")
    public AjaxResult favoriteCount() {
        return AjaxResult.success(postService.selectFavoriteCount());
    }

    /**
     * 关注
     * @return
     */
    @GetMapping("/follow-count")
    @ApiOperation("首页关注")
    public AjaxResult followCount() {
        return AjaxResult.success(postService.selectFollowCount(getUserId()));
    }

    /**
     * 项目推荐
     * @return
     */
    @GetMapping("/recommended")
    @ApiOperation("项目推荐")
    public AjaxResult recommended() {
        return AjaxResult.success(postService.selectViewCount());
    }

    @PostMapping("/copy")
    @ApiOperation("复制项目")
    public AjaxResult copy(@RequestBody TechPostDTO techPostDTO) {
        TechPostVO techPostVO = postService.getById(techPostDTO.getId());
        TechPost techPost = new TechPost();
        BeanUtil.copyProperties(techPostVO, techPost);
        String title = StrUtil.isNotBlank(techPostDTO.getTitle()) ? techPostDTO.getTitle() : techPostVO.getTitle();
        techPost.setTitle(title);
        String content = StrUtil.isNotBlank(techPostDTO.getContent()) ? techPostDTO.getContent() : techPostVO.getContent();
        techPost.setContent(content);
        String coverImage = StrUtil.isNotBlank(techPostDTO.getCoverImage()) ? techPostDTO.getCoverImage() : techPostVO.getCoverImage();
        techPost.setCoverImage(coverImage);
        techPost.setUserId(SecurityUtils.getUserId());
        techPost.setSource(techPostDTO.getId());
        techPost.setStatus(PostStatusEnum.PRIVATE.name());
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(techPostVO.getCode()) && techPostVO.getCode().startsWith("ssh")) {
            String repoName = techPostVO.getCode().substring(techPostVO.getCode().lastIndexOf("/")+1, techPostVO.getCode().lastIndexOf("."));
            LoginUser loginUser = getLoginUser();
            SysUser sysUser = sysUserService.selectUserPassnoById(loginUser.getUserId());
            SysUser sysUser1 = sysUserService.selectUserById(techPostVO.getUserId());
            String result = GiteaUtils.getForkRepoGiteaRepo(sysUser.getUserName(), sysUser.getPassno(),repoName,sysUser1.getUserName());
            map.put("code", result);
            techPost.setCode(result);
        }
        // 复制项目资源
        postService.copyPost(techPost);
        map.put("id", techPost.getId());
        return AjaxResult.success(map);
    }
}